package com.lxf.education.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lxf.education.pojo.TeacherPojo;
import com.lxf.education.pojo.UserPojo;
import com.lxf.education.service.Teacher_ResultService;
import com.lxf.education.service.UserService;
import com.lxf.education.utils.ResultVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.support.CaptchaType;

import io.swagger.annotations.ApiOperation;

import java.util.List;

/**
* @author:LuoXingFa;
* @version:Date:2022年4月18日下午4:10:32
*/
@Controller
@RequestMapping("/Teaching_evaluation_system")
public class UserController {
	//映射出service接口
	
	@Resource
	UserService userservice;
	
	@Resource
	UserPojo user;
	
	@Autowired
	HttpServletRequest request;

	@Resource
	Teacher_ResultService teacher_resultService;
	/**
	 * 验证码生成
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getVerifyCode")
	@ApiOperation(value = "登录模块生成的验证码")
	public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {
		HappyCaptcha.require(request, response).type(CaptchaType.WORD_NUMBER_LOWER).build().finish();
		HappyCaptcha.require(request, response).width(100).height(40);
	}
	
	/**
	 * //登录成功跳转到首页
	 * @param code 验证码
	 * @param request 
	 * @param response
	 * @param model
	 * @return
	 */
     @RequestMapping("/index")
     public String login(String code,HttpServletRequest request, HttpServletResponse response, Model model) {
         try {
             String username = request.getParameter("username");
             String password = request.getParameter("password");
             String remeber = request.getParameter("remember");
             //根据用户名查询到密码
             String pwd = userservice.findPWDByName(username);
             
             BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
             boolean matches = encoder.matches(password, pwd);//密码解密
			//记住密码的操作
			 if (remeber!=null) {
				 Cookie cookieUser = new Cookie("username", username);
				 Cookie cookiePwd = new Cookie("password", password);
				 //设置最大缓存时间为一周
				 cookieUser.setMaxAge(60*60*24*7);
				 cookiePwd.setMaxAge(60*60*24*7);
				 //加入cookie缓存
				 response.addCookie(cookieUser);
				 response.addCookie(cookiePwd);
			 }
			 boolean flag = HappyCaptcha.verification(request,code,true);//验证码校验
		         if(matches){
		         	    //加入视图中显示在前端
		        	    model.addAttribute("user", username);
		        	    //将该用户加入session缓存
		        	    request.getSession().setAttribute("user", username);
		             if(flag){
		             	//查询所有教师
						 List list = teacher_resultService.getAllTeacher();
						 model.addAttribute("list",list);
			                //返回到主界面
			                return "index";
			             }else {
			 	      		model.addAttribute("msg","验证码错误或不能为空");
			 				return "login";
			 		    } 
			  }else {
						model.addAttribute("msg", "用户名或密码错误!");
						HappyCaptcha.remove(request);//清除缓存，防止验证码二次使用
		            	return "login";
					}
                 
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null;
     }
     
     /**
      * @注册功能
      * @注册成功则跳转到登录界面
      * @param "userPojo"
      * @return
      */
     @RequestMapping("/User_register")
     public String Register(UserPojo user,Model model,HttpServletRequest request) {
     	 String uname = request.getParameter("user");
     	 UserPojo userPojo = userservice.findUserProfile(uname);
     	 if (userPojo==null){
			 UserPojo user1 = userservice.insertUser(user);
			 if (user1!=null) {
				 return "login";
			 }
		 }else {
			 model.addAttribute("mess","该用户名已存在，请重新输入");
			 return "redirect:/register";
		 }
		return null;
	} 
     
     /**
      * @获取重置密码的验证码
      */
     /**
      * @获取重置密码的验证码
      */
     @RequestMapping("/code")
     @ResponseBody
     public ResultVo getcodes(String mailAddress) {//使用参数接收前端传过来的数据
    	 //根据邮箱查找用户
    	 UserPojo user = userservice.findUserByEmail(mailAddress);
    	 if (user==null) {
			return ResultVo.getFailVo("该邮箱没有绑定用户，不能执行修改密码操作");
		}
    	 //将改邮箱绑定的用户存入session中
    	 request.getSession().setMaxInactiveInterval(60);
    	 request.getSession().setAttribute("username", user.getUname());
    	 
         return userservice.getCode(mailAddress);
     }
     /**
      * @根据验证码修改密码
      * @param "codeUpdateVo"
      * @return
      */
     @RequestMapping("/updateByCode")
     public String codeUpdatePwd(HttpServletRequest request,Model model) {
    	 //获取session中所存储的验证码与用户名
    	 HttpSession session = request.getSession();
    	 String vertifyCode = (String)session.getAttribute("vertifyCode");
    	 String name = (String)session.getAttribute("username");
     	 //获取前端的参数
    	 String username = request.getParameter("username");
    	 String code = request.getParameter("codes");
    	 String newPwd = request.getParameter("new_password");
    	 String reNewPwd = request.getParameter("re_new_password");
    	 
    	 //解密验证码
    	 BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    	 boolean matches = encoder.matches(code,vertifyCode);
    	
    	 //非空判断
    	 if (username==null&&username.equals(""))model.addAttribute("error", "用户名不能为空");
    	 if (!matches)model.addAttribute("error", "验证码不正确，请重新输入");
    	 if (newPwd==null&&newPwd.equals("")&&newPwd!=reNewPwd) model.addAttribute("error", "两次密码输入不一致，请认真检查后再填写");
			
    	 //运行修改密码方法
    	 userservice.updatePwdByCode(username,code,encoder.encode(newPwd),encoder.encode(reNewPwd));
    	 //将session缓存失效，避免重复使用
    	 session.invalidate();
    	 return "login";
     }

	/**
	 * @查看个人资料
	 * @param request
	 * @return
	 */
	@RequestMapping("/profile")
	public String getProfile(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		//获取session中的对象
		String name = (String)session.getAttribute("user");
		UserPojo user = userservice.findUserProfile(name);
		//将用户信息返回前端界面
		model.addAttribute("user", user);
		return "profiles/pProfile";
	}

	/**
	 * 退出登录操作
	 * @param request
	 * @return
	 */
	@RequestMapping("/loginout")
     public String loginout(HttpServletRequest request){

		 HttpSession session = request.getSession();
		 session.removeAttribute("user");
		 //退出登录并重定向到登录界面
     	return "redirect:/login";
	 }
}
